<template>
  <div class="w-full relative" ref="container" tabindex="-1">
    <a-form
      :layout="'inline'"
      autocomplete="off"
      class="select-text text-sm"
      @submit.prevent="onSubmit"
      @reset="onReset"
      role="search"
    >
      <a-input
        v-model="value"
        ref="input"
        :placeholder="$t('search_your_photos')"
        :disabled="showFilter"
        :class="[
          'w-full transition-all border-2 px-14 py-4 text-immich-fg/75',
          grayTheme ? 'dark:bg-immich-dark-gray' : 'dark:bg-immich-dark-bg',
          showSuggestions && isSearchSuggestions ? 'rounded-t-3xl' : 'rounded-3xl bg-gray-200',
          isSearchEnabled && !showFilter ? 'border-gray-200 dark:border-gray-700 bg-white' : 'border-transparent'
        ]"
        @focus="openDropdown"
        @input="onInput"
        role="combobox"
        :aria-controls="listboxId"
        :aria-activedescendant="selectedId || ''"
        :aria-expanded="showSuggestions && isSearchSuggestions"
        aria-autocomplete="list"
      >
        <template #prefix>
          <a-button
            type="text"
            :disabled="showFilter"
            :title="$t('search')"
            icon="search"
            @click="onSubmit"
          />
        </template>
        <template #suffix>
          <div class="flex items-center">
            <a-button
              v-if="showClearIcon"
              type="text"
              :title="$t('clear')"
              icon="close"
              @click="onClear"
            />
            <a-button
              type="text"
              :title="$t('show_search_options')"
              icon="setting"
              @click="onFilterClick"
            />
          </div>
        </template>
      </a-input>

      <!-- SEARCH HISTORY BOX -->
      <SearchHistoryBox
        ref="searchHistoryBox"
        :id="listboxId"
        :searchQuery="value"
        :isOpen="showSuggestions"
        @clearAllSearchTerms="clearAllSearchTerms"
        @clearSearchTerm="clearSearchTerm"
        @selectSearchTerm="onHistoryTermClick"
        @activeSelectionChange="onActiveSelectionChange"
      />
    </a-form>

    <!-- Clear Icon -->
    <div
      class="absolute inset-y-0 flex items-center pl-6 transition-all"
      :class="showClearIcon ? 'right-14' : 'right-2'"
    >
      <a-button
        type="text"
        :title="$t('show_search_options')"
        icon="setting"
        @click="onFilterClick"
      />
    </div>

    <!-- Clear Button -->
    <div v-if="showClearIcon" class="absolute inset-y-0 right-0 flex items-center pr-2">
      <a-button
        type="text"
        :title="$t('clear')"
        icon="close"
        @click="onClear"
      />
    </div>

    <!-- Submit Button -->
    <div class="absolute inset-y-0 left-0 flex items-center pl-2">
      <a-button
        type="submit"
        :disabled="showFilter"
        :title="$t('search')"
        icon="search"
        @click="onSubmit"
      />
    </div>
  </div>
</template>

<script>
import Vue from 'vue';
import { debounce } from 'lodash';
import SearchHistoryBox from './search-history-box.vue';
import { AppRoute } from '@/constants';
import { mapActions } from 'vuex';

export default Vue.extend({
  name: 'SearchBar',
  components: {
    SearchHistoryBox,
  },
  props: {
    grayTheme: {
      type: Boolean,
      required: true,
    },
  },
  data() {
    return {
      value: '',
      showSuggestions: false,
      showFilter: false,
      isSearchSuggestions: false,
      selectedId: undefined,
      listboxId: `search-bar-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
      input: null,
      searchHistoryBox: null,
      isSearchEnabled: false,
    };
  },
  computed: {
    showClearIcon() {
      return this.value.length > 0;
    },
  },
  methods: {
    ...mapActions(['saveSearchTerm', 'clearSearchTerm', 'clearAllSearchTerms']),
    openDropdown() {
      this.showSuggestions = true;
    },
    closeDropdown() {
      this.showSuggestions = false;
      if (this.searchHistoryBox) {
        this.searchHistoryBox.clearSelection();
      }
    },
    onInput: debounce(function () {
      this.openDropdown();
      if (this.searchHistoryBox) {
        this.searchHistoryBox.clearSelection();
      }
    }, 300),
    onSubmit() {
      if (!this.value) return;
      this.saveSearchTerm(this.value);
      this.handleSearch({ query: this.value });
    },
    onReset() {
      this.value = '';
    },
    onClear() {
      this.value = '';
      if (this.input) {
        this.input.focus();
      }
    },
    onFilterClick() {
      this.showFilter = !this.showFilter;
      this.value = '';
      if (this.showFilter) {
        this.closeDropdown();
      }
    },
    async handleSearch(payload) {
      this.closeDropdown();
      this.showFilter = false;
      this.isSearchEnabled = false;
      await this.$router.push({ path: AppRoute.SEARCH, query: payload });
    },
    onHistoryTermClick(term) {
      this.value = term;
      this.handleSearch({ query: term });
    },
    onActiveSelectionChange(id) {
      this.selectedId = id;
    },
    onFocusIn() {
      this.isSearchEnabled = true;
    },
    onFocusOut() {
      const focusOutTimer = setTimeout(() => {
        if (this.isSearchEnabled) {
          this.closeDropdown();
          this.isSearchEnabled = false;
          this.showFilter = false;
        }
      }, 100);

      clearTimeout(focusOutTimer);
    },
  },
  beforeDestroy() {
    this.onInput.cancel();
  },
});
</script>

<style scoped>
/* 样式保持与原始文件一致 */
</style>